﻿using System;
using System.Linq;
using Wolfpack.Periscope.Core.Extensions;
using Wolfpack.Periscope.Core.Interfaces.Entities;
using Wolfpack.Periscope.Core.Interfaces.Events;

namespace Wolfpack.Periscope.Core
{    
    public partial class Dashboard
    {
        private void HandleAddWidgetToPanelEvent(AddWidgetToPanelCommand args)
        {
            var config = _repository.Load();
            var targetPanel = config.Panels.FindOrFail(args.Content.TargetPanelId);

            if (targetPanel.Widgets.Any(x => x.Id.Equals(args.Content.Id)))
                throw new InvalidOperationException(string.Format("Panel already contains a widget with Id '{0}'!",
                    args.Content.Id));

            var instance = new WidgetInstance
            {
                RendererId = args.Content.RendererId,
                Column = args.Content.Column,
                CssTemplate = args.Content.ScriptPack,
                Description = args.Content.Description,
                Height = args.Content.Height,
                Id = args.Content.Id,
                MarkupTemplate = args.Content.ScriptPack,
                Row = args.Content.Row,
                SampleTemplate = args.Content.ScriptPack,
                ScriptTemplate = args.Content.ScriptPack,
                Title = args.Content.Title,
                Width = args.Content.Width
            };

            if (args.Content.TemplateData != null)
                instance.TemplateData = args.Content.TemplateData
                    .ToDictionary(x => x.Name, x => x.Value);

            targetPanel.AddWidget(instance);
            _repository.Save(config);

            _infrastructure.MessageBus.Publish(new WidgetAddedEvent(this, new WidgetReference
            {
                PanelId = args.Content.TargetPanelId,
                WidgetId = args.Content.Id                
            }));
        }
    }
}